#!/usr/bin/php
<?php
/*
 *   This file is part of poat.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 */

date_default_timezone_set('UTC'); 
$starttime=time();
echo "Started: ". date('Y-m-d H:i',time())."\n";

define('CURRENT_DIR',dirname(__FILE__));
$last_slash = strrpos(CURRENT_DIR, "/");
define('SYSDIR',substr(CURRENT_DIR, 0, $last_slash));

DEFINE('TEMPDIR','/home/poat/tmp/pofiles');
DEFINE('STATFILE','stats');
DEFINE('SCRIPT',CURRENT_DIR.'/msgstats.sh');
DEFINE('GETFILE',CURRENT_DIR.'/getfile.php');

if (!file_exists(TEMPDIR)) {
	mkdir(TEMPDIR);	
}

if (file_exists(TEMPDIR.'/run.log')) {
	copy(TEMPDIR.'/run.log',TEMPDIR.'/run.log.bak');
	unlink(TEMPDIR.'/run.log');
}

$runout = fopen(TEMPDIR.'/run.log', 'a');
fwrite($runout,"Started: ". date('Y-m-d H:i',time())."\n");

$debugenabled=false;
$maildebugenabled=false;
$dbdebugenabled=false;
error_reporting(0);
ini_set('display_errors', false);

include_once(CURRENT_DIR."/func_stats.php");
include_once(SYSDIR."/configs/dbconf.php");

require_once(SYSDIR."/includes/phpsvnclient.php");

require_once(SYSDIR."/class/dbmanager.class.php");
require_once(SYSDIR."/class/loader.class.php");
require_once(SYSDIR."/includes/util.func.php");

require_once(SYSDIR."/class/project.class.php");
require_once(SYSDIR."/class/user.class.php");
require_once(SYSDIR."/class/files.class.php");
require_once(SYSDIR."/class/team.class.php");
require_once(SYSDIR."/class/history.class.php");
include_once(SYSDIR."func/deltree.inc.php");
require_once(SYSDIR."/class/def.class.php");

$db = new dbmanager(DB_HOST,DB_USER,DB_PASS);

$db->connect(DB_NAME);
$loader = new loader($db);

/* LOAD DEFINITIONS */
$defs = simplexml_load_file(SYSDIR."/configs/definitions.xml");
foreach($defs->definition as $def) {
   eval("define('{$def->name}', '{$def->value}');");
}

$defs = simplexml_load_file(SYSDIR."/configs/tables.xml");
foreach($defs->table as $def) {
   eval("define('{$def->name}', '{$def->value}');");
}

$def = new def;
$list = $loader->loadList($def);

foreach($list as $obj) {
   eval("define('{$obj->id}', '{$obj->value}');");
}

if (ENABLE_CUSTOM_SMTP == 'true') {
	debug("Using custom SMTP");
	ini_set("smtp",SMTP_HOST);
	ini_set("smtp_port",SMTP_PORT);
}

/* END */

function logthis($out,$text,$time = true) {
	//echo today()." - ".$text."\n";
	if ($time===false) {
		fwrite($out,$text."\n");
	} else {
		fwrite($out,today()." - ".$text."\n");	
	}
	
}

$totalfiles=0;
$totalprojects=0;
$totalfailedfiles=0;

/* GET ACTIVE PROJECT LIST */
$prj = new project;
$prj->status=STATUS_ACTIVE;
$prjlist = $loader->loadListBy($prj,$prj->listByStatus());

//debug($prjlist);

foreach ($prjlist as $inprj) {
	$totalprojects+=1;
	logthis($runout,"============= PROJECT ".$inprj->id." - ".$inprj->name." =============");
	
	/* GET ACTIVE SUBPROJECT LIST */
	$sprj = new project;
	$sprj->status=STATUS_ACTIVE;
	$sprj->parent=$inprj->id;
	$sprjlist = $loader->loadListBy($sprj,$sprj->listByAny());	

	//debug($sprjlist);
	
	foreach ($sprjlist as $insub) {
		logthis($runout,"============= SUBPROJECT ".$insub->id." - ".$insub->name." =============");
		/* GET ACTIVE TEAM LIST */
		$team = new team;
		$team->prid=$inprj->id;
		$team->subprj=$insub->id;
		$teamlist = $loader->loadListBy($team,$team->listByReady());
		
		//debug($teamlist);
		
		foreach ($teamlist as $inteam) {
			logthis($runout,"============= TEAM ".$inteam->id." - ".$inteam->name. " =============");
			/* GET FILE LIST */
			$file = new files($inprj->id);
			$file->teamid=$inteam->id;
			$file->subprj=$insub->id;
			$filelist = $loader->loadListBy($file,$file->loadfiltered());
			
			//debug($filelist);

			foreach ($filelist as $infile) {
				$totalfiles+=1;
				logthis($runout,"============= FILE ".$infile->id." - ".$infile->name." =============");
				$url=$inprj->path . str_replace('$LANG',$inteam->lang,$insub->path);	
				$url .= '/'.$infile->name;
				$filename=TEMPDIR.'/'.$infile->name;
				logthis($runout,"Get File ".$url);
				for ($i=1;$i<=3;$i++) {
					exec(GETFILE." '".SVN_ROOT."' '".$url."' '".$filename."'");
					if (file_exists($filename)) {
						break;
					}
					logthis($runout,"Try get file again ".$i);
				}
				
				if (file_exists($filename)) {
					logthis($runout,"Processing File ".$filename);	
					
					/* CALL MSGFMT */
					logthis($runout,"MSGFMT");
					$in = exec(SCRIPT." ".$filename);				
					/* REMOVE THE FILE */
					logthis($runout,"Remove the File");
					unlink($filename);
					unlink(CURRENT_DIR."/messages.mo");
	
					/* READ GENERATED STATS */
					//$in = file_get_contents(TEMPDIR.'/'.STATFILE);
					$stats = explode(";", $in);
					logthis($runout,"Read Stats [".count($stats)."]");
					//print_r($stats);

					if (count($stats)==3) {
						$translated=$stats[0];
						$untranslated=$stats[1];
						$fuzzy=$stats[2];
						$control = $fuzzy + $untranslated;
							
						/* UPDATE FILE */
						logthis($runout,"Update the file");
						$infile->translated=$translated;
						$infile->fuzzy=$fuzzy;
						$infile->untranslated=$untranslated;
						$loader->execute($infile->stats());
						
						if ($control > 0 and $infile->statusid == FILE_STATUS_DONE) {
							logthis($runout,"Send mail");
							$infile->statusid = FILE_STATUS_CHKPND;
							$infile->comment = BOT_STAT_COMMENT;
							$infile->stamp=util::hashcode($infile->id);
							$loader->update($infile);
							
							$his = new history($inprj->id);
							$his->statusid=$infile->statusid;
							$his->fileid=$infile->id;
							$his->userid=BOT_USER;
							$his->comment=$infile->comment;
							$loader->save($his);
							/* SEND MAIL */
							sendStatUpdateMail($infile,$inprj);
						}
						logthis($runout,"============= FINISHED FILE ".$infile->name. " =============");						
					} else {
						$totalfailedfiles+=1;
						logthis($runout,"FAILED PROCESSING STATS ".$infile->name);
					}
				} else {
					$totalfailedfiles+=1;
					logthis($runout,"FAILED GETTING FILE ".$infile->name);
				}
			}
			logthis($runout,"============= FINISHED TEAM ".$inteam->id." =============");
		}
		logthis($runout,"============= FINISHED SUBPROJECT ".$insub->id." =============");	
	}

	/* UPDATE PROJECT */
	logthis($runout,"============= FINISHED PROJECT ".$inprj->id." =============");
	$inprj->statsupdated=util::now();
	$loader->execute($inprj->stats());	

}

$db->close();
$endtime=time();
logthis($runout,"Finished: ". date('Y-m-d H:i',time()),false);
logthis($runout,"============= * =============",false);
$statstext = "Projects processed: ".$totalprojects."\nFiles processed: ".$totalfiles." of which ".$totalfailedfiles." failed.";
logthis($runout,$statstext,false);
logthis($runout,"Process time: ".date("H:i.s",$endtime-$starttime),false);
fclose($runout);

echo "Finished: ". date('Y-m-d H:i',time())."\n";
echo $statstext."\n";
echo "Process time: ".date("H:i.s",$endtime-$starttime)."\n";

sendLogFile("statslog@os-translation.com.ar",TEMPDIR.'/run.log');

deltree(TEMPDIR);
?>